import 'dart:async';
import 'dart:developer';

import 'package:flutter/services.dart';

class LjyHomeChannel {
  final MethodChannel _channel = const MethodChannel('flutter_home_plugin/methods');
  final StreamController<MethodCall> _methodStreamController = StreamController<MethodCall>.broadcast();
  Stream<MethodCall> get _methodStream => _methodStreamController.stream;


  static final LjyHomeChannel _instance = LjyHomeChannel._internal();
  static LjyHomeChannel get instance => _instance;

  LjyHomeChannel._internal() {
    _channel.setMethodCallHandler(
      (MethodCall call) async {
        _methodStreamController.add(call);
      },
    );

    _methodStream.listen((MethodCall call) {
      print('flutter收到方法名:${call.method},参数:${call.arguments}');
      if (call.method == 'onDataReceived') {
        int data = call.arguments['data'];
        String msg = call.arguments['msg'];
        log("onDataReceived data:$data,msg:$msg");
      }
    });
  }

  Future<int> writeData(int data, String msg) async {
    int result = -100;
    try {
      await _channel.invokeMethod('writeData', {'data': data, 'msg': msg})
      .then<int>((d) => result = d)
      .onError((error, StackTrace) => result = -1);
      if (result != 0) {
        print("xiandao result:$result");
      }
      return result;
    } catch (e, stack) {
      print("1Failed to Invoke: '${e.toString()}'.");
      print("2Failed to Invoke: '${stack.toString()}'.");
      return result;
    }
  }
}